<template>
	<uni-nav-bar
		v-if="!isWxBrowser"
		left-icon="left"
		title="搜索"
		:fixed="navBarFixed"
		@clickLeft="goBack"
		height="100rpx"
	/>
	<view class="search-container">
		<view class="top-search" :style="{ top: isWxBrowser ? '0' : '100rpx' }">
			<f-searchBar
				@searchSuccess="searchSuccess"
				@changeInput="changeInput"
				@searchClicked="searchClicked"
				ref="topSearch"
			/>
		</view>
		<view class="every-searching-content">
			<view class="show-detail">
				<img src="../../static/common/fire.png" alt="" />
				<view class="title-txt"> 大家都在搜 </view>
			</view>
			<view class="show-content">
				<view
					:class="currentItem === index ? 'active-item-list' : ''"
					class="item-list"
					v-for="(item, index) in everySearchingList"
					:key="item"
					@click="autoSearch(item, index)"
				>
					{{ item }}</view
				>
			</view>
		</view>
		<!-- 猜你喜欢 -->
		<view v-if="isShow" class="guess-you-like" :style="{ top: isWxBrowser ? '132rpx' : '228rpx' }">
			<view class="show-detail-title">猜你喜欢 </view>
			<view class="change-btn-content" @click="changeShowList">
				<img src="../../static/common/cycle.png" alt="" />
				<view class="change-btn-text"> 换一批</view>
			</view>
		</view>
		<view v-else class="tip-info" :style="{ top: isWxBrowser ? '132rpx' : '228rpx' }">
			<view class="title-detail"
				>为您找到 <span class="result-num">{{ total }}</span
				>条搜索结果</view
			>
			<view class="filter-btn">
				<f-filter-command-drawer @getFilterData="getFilterData" @changeDrawer="changeDrawer" />
			</view>
		</view>
		<view class="goods-detail">
			<f-common-singleGoods-card2
				:data="list"
				v-if="isShowScrollList"
				@getCurrentItem="getCurrentItem"
			/>

			<f-scroll-list
				v-else
				:status="loadMore.status"
				:showIcon="loadMore.showIcon"
				:color="loadMore.color"
				:contentText="loadMore.contentText"
				:useLoadMore="list.length > 0 ? true : false"
			>
				<f-common-singleGoods-card2 :data="list" @getCurrentItem="getCurrentItem" />
			</f-scroll-list>
		</view>
		<view class="bottom-btn" @click="posterShare" v-show="isShowShareBtn && total > 0">
			<view class="share-btn"> 分享好友</view>
		</view>
		<!-- 找相似 -->
		<f-search-find-similarities ref="findSimilarities" />
		<!-- 海报分享弹窗 -->
		<f-poster-shareModal
			v-if="show"
			ref="posterShareRef"
			:Data="showCardInfo"
			:qrCode="qrCode"
			:shareCode="shareCode"
			@cancel="cancelPoster"
		/>
	</view>
</template>

<script setup>
	import { computed, reactive, ref, watch } from 'vue';
	import sheep from '@/sheep';
	import {
		onLoad,
		onShow,
		onPageScroll,
		onReachBottom,
		onPullDownRefresh,
	} from '@dcloudio/uni-app';
	import _ from 'lodash';
	import searchApi from './../../sheep/api/search.js';
	import cartApi from './../../sheep/api/cart.js';
	import QRCode from 'qrcode';

	const loadMore = reactive({
		status: '',
		showIcon: true,
		color: '',
		contentText: {},
	});
	const isShowScrollList = ref(false);
	const everySearchingList = ref([]);
	const isShowShareBtn = ref(false);
	const list = ref([]);
	const state = reactive({
		historyList: [],
	});
	const isShow = ref(true);
	const findSimilarities = ref(null);
	const formInput = ref('');
	const isWxBrowser = computed(() => sheep.$store('app').isWxBrowser); //代码运行环境
	const navBarFixed = ref(true);

	const searchSuccess = (val) => {
		console.log(val);
		findSimilarities.value.openDialog(val);
	};
	// 搜索
	function onSearch(keyword) {
		if (!keyword) return;
		saveSearchHistory(keyword);
		sheep.$router.go('/pages/goods/list', {
			keyword,
		});
	}
	const changeInput = (val) => {
		//输入框为空
		if (!val) {
			isShow.value = true; //是否显示猜你喜欢
			isShowShareBtn.value = false; //是否显示分享好友按钮
			isShowScrollList.value = true; //是否展示下滑组件
			changeShowList(); //重新展示页面数据
			currentItem.value = null;
		}
	};
	/**
	 * 抽屉状态更新
	 */
	const changeDrawer = () => {
		isShowShareBtn.value = !isShowShareBtn.value;
		let idRef = document.getElementById('app');
		if (!isShowShareBtn.value) {
			idRef.style.overflow = 'hidden';
			navBarFixed.value = false;
		} else {
			idRef.style.overflow = 'visible';
			navBarFixed.value = true;
		}
	};
	//换一批
	const changeShowList = () => {
		isShowScrollList.value = true;
		searchApi.getLikesList().then((res) => {
			list.value = res.data;
		});
	};
	const getCurrentItem = (item) => {
		console.log(item, 'item==');
		sheep.$router.go('/pages/index/goodsDetail', { id: item.id });
	};
	const currentItem = ref(null);
	const topSearch = ref();
	const inputText = ref('');
	const pageIndex = ref(1);
	const total = ref(0);
	const filterData = ref({});
	const filterFlag = ref('0'); //0： 点击了搜索按钮  1：点击了筛选面板的确定按钮
	const autoSearch = (item, index) => {
		//点击了热搜词，自动将点击项回显到输入框内，并执行搜索请求
		topSearch.value.setFormInputText(item);
		currentItem.value = index;
		searchClicked(item);
	};

	const getFilterData = (info) => {
		filterData.value = { ...info };
		filterFlag.value = '1';
		pageIndex.value = 1; //每次点击筛选面板中的搜索按钮，将分页参数为 1
		let data = {
			name: inputText.value,
			pageNumber: pageIndex.value,
			pageSize: 20,
			special: false,
			publicNewSelection: false,
			styles: info.styleType,
			genders: info.genderList,
			festivals: info.holidayTheme,
			hues: info.colorSystem,
			printTypes: info.fabricSize,
		};
		getDataList(data);
	};
	const searchClicked = (val) => {
		inputText.value = val;
		isShowShareBtn.value = true;
		isShow.value = false;
		isShowScrollList.value = false;
		filterFlag.value = '0';
		pageIndex.value = 1; //每次点击输入框内的搜索按钮，将分页参数为 1
		let data = {
			pageNumber: pageIndex.value,
			pageSize: 20,
			name: inputText.value,
		};
		getDataList(data);
	};
	const getDataList = (data) => {
		console.log('requestData=====>>', data);
		searchApi.searchTextDetail(data).then((res) => {
			if (data.pageNumber === 1) {
				//不需要将新数据合并到原列表的情况，即 下拉和每次点击筛选面板的确认按钮时
				// 当接口返回的数据为空时,仍然不会置空页面,给出弹窗提示即可
				if (res.data.records.length > 0) {
					list.value = res.data.records;
					total.value = res.data.total;
				} else {
					return uni.showToast({
						title: '暂未查询到相关数据',
						icon: 'none',
					});
				}
			} else {
				//需要将新数据合并到原列表的情况
				if (res.data.records.length > 0) {
					list.value = _.concat(list.value, res.data.records);
					total.value = res.data.total;
				} else {
					return uni.showToast({
						title: '暂未查询到相关数据',
						icon: 'none',
					});
				}
			}
			if (total.value === res.data.total) {
				loadMore.status = 'no-more';
			}
		});
	};
	const getHistory = () => {
		searchApi.getHistoryList().then((res) => {
			everySearchingList.value = res.data;
		});
	};
	onLoad(() => {
		state.historyList = uni.getStorageSync('searchHistory') || [];
		getHistory();
		changeShowList();
	});

	const goBack = () => {
		sheep.$router.back();
	};
	/**
	 * reachBottom 触底事件
	 */
	onReachBottom(() => {
		loadMore.status = 'loading';
		pageIndex.value += 1;
		if (!isShowScrollList.value) {
			if (list.value.length !== total.value) {
				loadMore.status = 'more';
				//1：根据筛选面板查询结果上划 2：根据输入框搜索按钮查询结果上划
				let data = {
					pageNumber: pageIndex.value,
					pageSize: 20,
					name: inputText.value,
				};
				let data2 = {
					name: inputText.value,
					pageNumber: pageIndex.value,
					pageSize: 20,
					special: false,
					publicNewSelection: false,
					styles: filterData.value.styleType,
					genders: filterData.value.genderList,
					festivals: filterData.value.holidayTheme,
					hues: filterData.value.colorSystem,
					printTypes: filterData.value.fabricSize,
				};
				// 判断是点击输入框中搜索按钮,还是点击了筛选面板中的确定按钮
				filterFlag.value === '1' ? getDataList(data2) : getDataList(data);
			} else {
				loadMore.status = 'no-more';
			}
		}
	});
	const loading = ref(null);
	onPullDownRefresh(async () => {
		loading.value = true;
		uni.showLoading({
			title: '正在刷新...',
			mask: true,
			fail: () => {
				uni.hideLoading();
			},
		});
		setTimeout(function () {
			//此处延时器不能清除，否则会导致下拉之后，下拉icon永远停留在页面
			//无法再次下拉
			uni.stopPullDownRefresh();
			loading.value = false;
			uni.hideLoading();
		}, 800);
		if (!isShowScrollList.value) {
			//1：根据筛选面板查询结果下拉 2：根据输入框搜索按钮查询结果下拉
			let data = {
				pageNumber: 1,
				pageSize: 20,
				name: inputText.value,
			};
			let data2 = {
				pageNumber: 1,
				pageSize: 20,
				special: false,
				publicNewSelection: false,
				styles: filterData.value.styleType,
				genders: filterData.value.genderList,
				festivals: filterData.value.holidayTheme,
				hues: filterData.value.colorSystem,
				printTypes: filterData.value.fabricSize,
			};
			// 判断是点击输入框中搜索按钮,还是点击了筛选面板中的确定按钮
			filterFlag.value === '1' ? getDataList(data2) : getDataList(data);
		}
	});

	// 海报分享
	const showCard = ref('');
	const show = ref(false);
	const showInfoList = ref([]);
	const shareCode = ref('');
	const qrCode = ref('');
	const showCardInfo = ref([]);
	// 点击分享按钮事件
	const posterShare = (e) => {
		showInfoList.value = list.value.slice(0, 20); //经沟通，暂定为20条
		let data = {
			imageItems: dealWithDataList(showInfoList.value),
		};
		// 获取二维码和分享码
		cartApi.getShareQrCode(data).then((res) => {
			// 生成二维码
			QRCode.toDataURL(res.data?.qrCode)
				.then((url) => {
					console.log(url);
					qrCode.value = url || '';
				})
				.catch((err) => {
					console.error(err);
				});
			show.value = e;
			showCardInfo.value = renameData(showInfoList.value); //处理用以好友分享的数据
			shareCode.value = res.data?.no;
		});
	};
	const renameData = (list) => {
		return list.map((item) => {
			return {
				imageThumbnailUrl: item.thumbnailUrl,
				imageName: item.name,
			};
		});
	};
	const dealWithDataList = (list) => {
		return list.map((item) => {
			return {
				imageId: item.id,
				printType: item.size,
			};
		});
	};
	const cancelPoster = () => {
		show.value = false;
	};
</script>

<style lang="scss" scoped>
	.search-container {
		.top-search {
			position: fixed;
			left: 0;
			right: 0;
			width: 100%;
			padding: 32rpx;
			box-sizing: border-box;
			// top: 100rpx;
			background-color: #eef0f2;
		}
		.every-searching-content {
			margin-top: 126rpx;
			.show-detail {
				padding: 4rpx 32rpx;
				display: flex;
				.title-txt {
					height: 40rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #111111;
					text-align: left;
					font-style: normal;
				}
				img {
					width: 36rpx;
					height: 36rpx;
				}
			}
			.show-content {
				width: 688rpx;
				margin: 0 auto;
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				.item-list {
					width: 340rpx;
					height: 36rpx;
					margin-top: 20rpx;
					display: flex;
					align-items: center;
					justify-content: flex-start;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #111111;
					font-style: normal;
				}
				.active-item-list {
					color: #ff6c01;
				}
			}
		}
		.guess-you-like {
			height: 54rpx;
			margin-top: 44rpx;
			padding: 0 32rpx;
			position: sticky;
			background-color: #eef0f2;
			// top: 228rpx;
			display: flex;
			.show-detail-title {
				flex: 5;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #111111;
				line-height: 44rpx;
				text-align: left;
				font-style: normal;
			}
			.change-btn-content {
				display: flex;
				align-items: center;
				img {
					width: 27rpx;
					height: 27rpx;
				}
				.change-btn-text {
					padding-left: 4rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #111111;
					line-height: 36rpx;
					text-align: left;
					font-style: normal;
				}
			}
		}
		.tip-info {
			margin-top: 32rpx;
			position: sticky;
			background-color: #eef0f2;
			padding: 0 0 20rpx 32rpx;
			top: 228rpx;
			display: flex;
			justify-content: space-between;
			.title-detail {
				flex: 1;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #111111;
				line-height: 44rpx;
				text-align: left;
				font-style: normal;

				.result-num {
					color: #ff6c01;
					margin-left: -10rpx;
					padding: 0 4rpx;
				}
			}

			.filter-btn {
				width: 132rpx;
				height: 52rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.goods-detail {
			padding: 0 32rpx 200rpx;
		}

		.bottom-btn {
			width: 748rpx;
			height: 178rpx;
			background: #ffffff;
			position: fixed;
			top: 95%;
			left: 50%;
			transform: translate(-50%, -50%);
			display: flex;
			align-items: center;
			justify-content: center;

			.share-btn {
				width: 686rpx;
				height: 88rpx;
				background: #111111;
				border-radius: 60rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #ffffff;
				line-height: 44rpx;
				letter-spacing: 1px;
				text-align: right;
				font-style: normal;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
	::v-deep .uni-scroll-view {
		position: initial !important;
	}
</style>
